// pages/question/question.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    maxHeight: "1100rpx",
    submit:false,
    answerArray:[],
    answerMatrix:[],
    rightArray:[],
    collectList:[],
    questionList:[],
    idArray:[],
    countDownNum:'',
    min:0,
    second:0,
    questionNum:5,
    bookId:1,
    chapterId:1,
    bookAbbr:'',
    source:"",
    current:0,
    minusHeight:wx.getStorageSync('statusBarHeight')+wx.getStorageSync('navigationBarHeight'),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let chapterId = options.chapterId
    let chapterAbbr = options.chapterAbbr
    let bookAbbr = options.bookAbbr
    let source = options.source
    this.setData({
      bookId:options.bookId,
      chapterId:chapterId,
      bookAbbr:bookAbbr,
      source:source,
    })
    let app = getApp()
    if(source == "review"){
      wx.request({
        url: app.globalData.url + '/question/review',
        data: {
          bookId: options.bookId,
          openId:app.globalData.userInfo.openid,
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success: result => {
          let questionList = result.data.data
          this.processQuestionList(questionList,bookAbbr,chapterAbbr)
        }
      })
    }else{
      wx.request({
        url: app.globalData.url + '/question/practice',
        data: {
          chapterId: chapterId,
          openId:app.globalData.userInfo.openid,
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success: result => {
          let questionList = result.data.data
          this.processQuestionList(questionList,bookAbbr,chapterAbbr)
        }
      })
    }
    
  },
  processQuestionList:function(questionList,bookAbbr,chapterAbbr){
    
    this.setData({questionNum:questionList.length})
    let answerArray = new Array()
    let rightArray = new Array()
    let answerMatrix = new Array()
    let collectList = new Array()

    for(let i = 0; i < questionList.length; ++i){
      answerMatrix.push([0,0,0,0])
      answerArray.push("?")
      collectList.push(0)
      rightArray.push(questionList[i].rightOption)
      let multiple = questionList[i].multiple == 1 ? '多选' : '单选'
      questionList[i].title = bookAbbr + "-" + chapterAbbr + "-" + multiple
    }
    this.setData({
      questionList:questionList,
      answerArray:answerArray,
      answerMatrix:answerMatrix,
      rightArray:rightArray,
      collectList:collectList,
    })
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    setInterval(()=>{
      
      let min = this.data.min
      let second = this.data.second

      if(second + 1 == 60){
        min = min + 1
        second = 0
      }else{
        second = second + 1
      }
      let countDownNum = ""
      let _min = min
      let _second = second
      if(min < 10){
        _min = "0" + min 
      }
      if(second < 10){
        _second = "0" + second
      }

      this.setData({
        min:min,
        second:second,
        countDownNum:_min+':'+_second
      })
    }, 1000);
    setTimeout(() => {
      var query = wx.createSelectorQuery();
      query.select('.container').boundingClientRect()
      query.exec((res) => {
        this.setData({maxHeight:res[0].height + "px"})
      })
    }, 500)
  },
  select: function(e){
    let option = e.currentTarget.dataset.option
    let id = parseInt(e.currentTarget.dataset.id)
    let index = parseInt(e.currentTarget.dataset.index)
    
    let optionNum = 0
    switch(option){
      case 'A':
        optionNum = 0
        break
      case 'B':
        optionNum = 1
        break
      case 'C':
        optionNum = 2
        break
      case 'D':
        optionNum = 3
        break
    }
    
    let answerMatrix = this.data.answerMatrix
    let answerArray = this.data.answerArray
    if(this.data.questionList[index].multiple == 0){
      answerArray[index] = option
      answerMatrix[index] = [0,0,0,0]
      answerMatrix[index][optionNum] = 1

    }else{
      if(answerMatrix[index][optionNum] == 0){
        answerMatrix[index][optionNum] = 1
      }else{
        answerMatrix[index][optionNum] = 0
      }
      
      if(answerArray[index] == "?"){
        answerArray[index] = option
      }else{
        if(answerArray[index].indexOf(option) == -1){
          answerArray[index] = answerArray[index] + option
        }else{
          let temp = answerArray[index].split("")
          
          temp[temp.indexOf(option)] = ''
          
          answerArray[index] = temp.join('')
          
        }
      }
      let str = answerArray[index].split("").sort(function(a,b){return a.localeCompare(b)})
      answerArray[index] = str.join('')
    }
    this.setData({
      answerArray:answerArray,
      answerMatrix:answerMatrix
    })
    let idArray = this.data.idArray
    idArray[index] = id
    this.setData({idArray:idArray})


    
  },
  preSubmit: function(e){
    let current = e.detail.current
    console.log(current)
    this.setData({current:current})
    if(current == 5){
      this.setData({submit:true})
    }else{
      this.setData({submit:false})
    }
    let height = wx.getSystemInfoSync().windowHeight;
    height = height - 40 - this.data.minusHeight
    if(current != this.data.questionNum){
      this.setData({maxHeight:"1150px"})
      setTimeout(() => {
        var query = wx.createSelectorQuery();
        query.select('.container' + current).boundingClientRect()
        query.exec((res) => {
          if(res[0].height < height){
            this.setData({maxHeight: height + "px"})
          }else{
            this.setData({maxHeight:res[0].height + "px"})
          }
          

        })
      }, 500)
    }else{
      
      
      this.setData({maxHeight:height + "px"})
    }


  },
  backToHome:function(){
    wx.switchTab({
      url: '/pages/home/home',
    })
  },
  checkAnswer:function(){
    let app = getApp()
    let isFinished = true
    for(let i = 0; i < this.data.questionNum; ++i){
      if(this.data.answerArray[i] == '?'){
        isFinished = false
        break
      }
    }
    if(isFinished){
      app.globalData.answerArray = this.data.answerArray
      app.globalData.questionList = this.data.questionList
      app.globalData.rightArray = this.data.rightArray
      wx.showLoading({
        title: '提交中...',
        mask:true,
      })      
      if(this.data.source == "review"){
         
         wx.request({
          url: app.globalData.url + '/question/checkreview',
          data: {
            openId: app.globalData.userInfo.openid,
            idArray: this.data.idArray.toString(),
            bookId: this.data.bookId,
          },
          header: {
            'content-type': 'application/json' // 默认值
          },
          success :res=> {
            wx.hideLoading()
            wx.redirectTo({
              url: '/pages/report/report?countDownNum='+this.data.countDownNum + "&bookAbbr=" + this.data.bookAbbr,
            })
          }
        })
      }else{
        //写进数据库
        wx.request({
          url: app.globalData.url + '/question/check',
          data: {
            openId: app.globalData.userInfo.openid,
            idArray: this.data.idArray.toString(),
            answerArray: this.data.answerArray.toString(),
            chapterId: this.data.chapterId,
            bookId: this.data.bookId,
            rightArray: this.data.rightArray.toString(),
          },
          header: {
            'content-type': 'application/json' // 默认值
          },
          success :res=> {
            
            wx.hideLoading()
            wx.redirectTo({
              url: '/pages/report/report?countDownNum='+this.data.countDownNum + "&bookAbbr=" + this.data.bookAbbr,
            })
          }
        })
      }
      
      
    }else{
      //表示题目还没有答完
      wx.showToast({
        title: '请完成作答再提交',
        icon: 'none',
        duration: 2000
      })    
    }
  },
  collectThis:function(){
    let current = this.data.current
    let collectList = this.data.collectList
    let app = getApp()
    
    wx.request({
      url: app.globalData.url + '/home/collect',
      data:{
        openId: app.globalData.userInfo.openid,
        dailyId: this.data.questionList[current].id,
        type:"question",
      },
      success :res=> {
        let result = res.data.status
        collectList[current] = 1
        this.setData({
          collectList:collectList,
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})